package com.lzq.his.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzq.his.common.CommonResp;
import com.lzq.his.domain.Student;
import com.lzq.his.domain.StudentExample;
import com.lzq.his.mapper.StudentMapper;
import com.lzq.his.req.StudentReq;
import com.lzq.his.resp.PageResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

@Service
public class StudentService {
    private final static Logger LOG = LoggerFactory.getLogger(StudentService.class);

    @Autowired
    private StudentMapper studentMapper;

    public PageResp<Student> selectAll(StudentReq req) {
        System.out.println(req);
        // 分页
        StudentExample categoryExample = new StudentExample();
        categoryExample.setOrderByClause(req.getOrderBy());
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<Student> list = studentMapper.selectByExample(categoryExample);

        PageInfo<Student> pageInfo = new PageInfo<>(list);
        LOG.info("总页数：{}", pageInfo.getPages());
        LOG.info("总行数：{}", pageInfo.getTotal());

        PageResp<Student> pageResp = new PageResp<>();
        pageResp.setList(list);
        pageResp.setTotal(pageInfo.getTotal());
        return pageResp;
    }


    public void deleteById(String id) {
        studentMapper.deleteByPrimaryKey(Integer.parseInt(id));
    }

    public void save(Student student) {
        if (student.getStudentid() == null) {
            Random random = new Random();
            student.setStudentid(random.nextInt());
            studentMapper.insert(student);
        } else {
            studentMapper.updateByPrimaryKeySelective(student);
            // 根据studentid 计算修改后的数据在哪一页
        }
    }

    public CommonResp save2(Student student) {
        CommonResp resp = new CommonResp();
        // 查询id是否存在
        if (studentMapper.selectByPrimaryKey(student.getStudentid()) != null) {
            resp.setSuccess(false);
            resp.setMessage("该id已存在");
            return resp;
        } else {
            studentMapper.insert(student);
            return resp;
        }

    }

    public int maxid() {
        return studentMapper.maxid();
    }
}
